import { _decorator, CCFloat, Component, Enum, Node, ResolutionPolicy, screen, Size, Vec3, view } from "cc";
const { ccclass, property } = _decorator;

/** UI自动适配组件 */
@ccclass
export default class UIAutoScale extends Component {
    @property({ readonly: true, displayName: "目标分辨率" })
    designSize: Size = new Size(720, 1280);
    @property({ readonly: true, displayName: "当前可见分辨率" })
    screenSize: Size = new Size(0, 0);
    @property({ type: CCFloat, displayName: "适配系数" })
    scalingFactor: number = 1.5;

    // 最大分辨率
    @property
    useMaxScale: boolean = false;
    @property({ type: CCFloat })
    maxScale: number = 1.0;


    start() {
        this.updateUIScale();
        view.on('canvas-resize', this.updateUIScale, this);
    }

    private updateUIScale() {
        this.screenSize = view.getVisibleSize();
        const designSize = this.designSize;
        let scale = 1;
        if (this.screenSize.width > this.screenSize.height) {
            // 横屏，按高度适配
            scale = (this.screenSize.height / designSize.height) * this.scalingFactor;
        } else {
            // 竖屏，按宽度适配
            scale = (this.screenSize.width / designSize.width);
        }

        // 最大缩放限制
        if (this.useMaxScale) {
            scale = Math.min(scale, this.maxScale);
        }
        this.node.scale = new Vec3(scale, scale, 1);

        // console.log(`节点:${this.node.name}  缩放:${scale}`)

        // 可选：输出调试信息
        // console.log(`UI缩放: ${scale}，方向: ${this.screenOrientation}`);
    }
}